import {
	register,
	register_box,
	register_header,
	register_box_form
} from "@/pages/register/index.module.scss"
import {Button, ColProps, Form, Input, message} from 'antd'
import {LoginFormsType, RegisterFormItemType, RegisterFormType} from '@/type/user'
import rules from '@/utils/rules'
import {generateRandomPhoneNumber} from '@/utils'
import {useCallback, useEffect} from 'react'
import {useNavigate} from 'react-router-dom'

const {Item, useForm} = Form

const loginFormLabelCol:ColProps = {
	span: 5
}

const btnStyle = {
	display: 'flex',
	alignItems: 'center',
	justifyContent: 'center',
	width: '100%',
	margin: '0 auto'
}

const registerForm: LoginFormsType<RegisterFormItemType>[] = [
	{
		label: '用户名',
		name: ['username'],
		rules: [
			{
				required: true,
				message: '请输入用户名'
			},
			{
				pattern: rules.subscriber('chineseName'),
				message: '请输入2到16位汉字'
			}
		]
	},
	{
		label: '密码',
		name: ['password'],
		rules: [
			{
				required: true,
				message: '请输入密码'
			},
		]
	},
	{
		label: '电话',
		name: ['phone'],
		rules: [
			{
				required: true,
				message: '请输入手机号'
			},
			{
				pattern: rules.subscriber('phone'),
				message: '请输入正确的手机号'
			}
		]
	}
]

const Register = () => {
	const navigate = useNavigate()

	const [form] = useForm()

	useEffect(() => {
		form.setFieldValue(["phone"], generateRandomPhoneNumber())
	}, [])

	const onFinish = useCallback((values: RegisterFormType) => {
		register(values).then(res => {
			if (res.code === 200) {
				message.success('注册成功进入登录页面')
				navigate("/login", {
					replace: true
				})
			}
		})
	}, [])

	return (
		<div className={register}>
			<div className={register_box}>
				<div className={register_header}>
					注册
				</div>
				<div className={register_box_form}>
					<Form
						form={form}
						labelCol={loginFormLabelCol}
						layout={'horizontal'}
						onFinish={onFinish}
					>
						{
							registerForm.map((item,index) => (
								<Item<RegisterFormType> {...item} key={index}>
									<Input></Input>
								</Item>
							))
						}
						<Item>
							<div style={btnStyle}>
								<Button block type={'primary'} htmlType={'submit'}>注册</Button>
							</div>
						</Item>
					</Form>
				</div>
			</div>
		</div>
	)
}


export default Register
